package tech.daoxuan.web.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 声明为组件并不能生效，还需要一些配置
 * {@link tech.daoxuan.web.config.WebConfig}
 * 在配置文件中，继承 {@link org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter}
 * 并重写 addInterceptors方法
 */
@Component
public class TimeInterceptor  implements HandlerInterceptor {
        Logger logger = LoggerFactory.getLogger(TimeInterceptor.class);
    /**
     * 返回的 true | false 可以控制 是否调用 controller 后面的方法
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        logger.info("preHandle is running ...");
        logger.info(((HandlerMethod)o).getBean().getClass().getName());
        logger.info(((HandlerMethod)o).getMethod().getName());

        httpServletRequest.setAttribute("startTime", new Date().getTime());
        return true;
    }

    /**
     * 如果handler抛异常，不会被调用
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("postHandle is running ...");

        Long start= (Long) httpServletRequest.getAttribute("startTime");
        logger.info("time spend 耗时："+(new Date().getTime()-start));
    }

    /**
     * 有无异常 总会调用
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("afterCompletion is running ....");
        Long start= (Long) httpServletRequest.getAttribute("startTime");
        logger.info("time spend 耗时："+(new Date().getTime()-start));

        logger.info("exception is ==="+e);
    }
}
